﻿using B.S.DataBase.MyProject.Domain.SalesReports;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Read.API.Applicantions.Command.Kanbans;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.KanbanHandler
{
    public class templateHandler2 : IRequestHandler<templateCommand2, APIResult<List<SalesReturns>>>
    {
        private readonly IBaseRepository<SalesReturns> _salesReturns;

        public templateHandler2(IBaseRepository<SalesReturns> salesReturns)
        {
            _salesReturns = salesReturns;
        }

        public async Task<APIResult<List<SalesReturns>>> Handle(templateCommand2 request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<SalesReturns>>()
            {
                Code = APIEnum.查询成功,
                Msg = APIEnum.查询成功.ToString(),
            };
            // 按物料名称分组并计算每个物料的退货总量
            var materialReturnStats = _salesReturns.GetAll().Result
                .GroupBy(x => x.WuliaoName)
                .Select(g => new
                {
                    WuliaoName = g.Key,
                    TotalReturn = g.Sum(x => x.ReturnNum),
                    Records = g.ToList()
                })
                .OrderByDescending(x => x.TotalReturn) // 按退货总量降序排序
                .ToList();

            // 获取退货数量最多的物料记录
            var mostReturnedMaterials = materialReturnStats
                .Take(100) // 取前10个退货最多的物料，可根据需求调整数量
                .SelectMany(x => x.Records) // 展开所有记录
                .ToList();

            result.data = mostReturnedMaterials;

            return await Task.FromResult(result);
        }
    }
}
